﻿package com.sgcc.nfc.lock.presentation.locks

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.sgcc.nfc.lock.core.network.NetworkResult
import com.sgcc.nfc.lock.domain.model.Lock
import com.sgcc.nfc.lock.domain.usecase.GetLockDetailUseCase
import dagger.hilt.android.lifecycle.HiltViewModel
import javax.inject.Inject
import kotlinx.coroutines.launch

@HiltViewModel
class LockDetailViewModel @Inject constructor(
    private val getLockDetailUseCase: GetLockDetailUseCase,
    savedStateHandle: SavedStateHandle
) : ViewModel() {

    private val lockId: Long = savedStateHandle.get<Long>("lockId") ?: 0L

    private val _lock = MutableLiveData<Lock?>()
    val lock: LiveData<Lock?> = _lock

    private val _isLoading = MutableLiveData(false)
    val isLoading: LiveData<Boolean> = _isLoading

    private val _message = MutableLiveData<String?>()
    val message: LiveData<String?> = _message

    init {
        loadDetail()
    }

    fun loadDetail() {
        viewModelScope.launch {
            _isLoading.value = true
            when (val result = getLockDetailUseCase(lockId)) {
                is NetworkResult.Success -> {
                    _lock.value = result.data
                    _message.value = null
                }
                is NetworkResult.Error -> _message.value = result.message
                NetworkResult.Loading -> _isLoading.value = true
            }
            _isLoading.value = false
        }
    }
}
